import type { ID } from "/@/api/models";
import type {
  AddRoleParams,
  AuthorizedRoleFunctionsParams,
  AuthorizedRoleUsersParams,
  RoleFunctionMenuItem,
  RoleItem,
} from "./models";
import req, { RequsetOptons } from "/@/api/req";

export enum Api {
  getRolesByName = "api/system/roles/getRolesByName",
  addRole = "api/system/roles/addRole",
  authorizedRoleFunctions = "api/system/roles/authorizedRoleFunctions",
  authorizedRoleUsers = "api/system/roles/authorizedRoleUsers",
  updateRole = "api/system/roles/updateRole",
  //获取角色用户列表
  getUsersByRoleId = "api/system/roles/getUsersByRoleId",
  deleteRoleByIds = "api/system/roles/deleteRoleByIds",
  getUsersTreeByRoleId = "api/system/roles/getUsersTreeByRoleId",
  removeAuthorizedRoleUsers = "api/system/roles/removeAuthorizedRoleUsers",
  getRoleById = "api/system/roles/getRoleById",
}

export enum PermissonApi {
  getFunctionsByUserId = "api/system/permissions/getFunctionsByUserId",
  getFunctions = "api/system/permissions/getFunctions",
}

export function addRole(data: AddRoleParams) {
  return req.post<RoleItem>({
    url: Api.addRole,
    data,
  });
}

export function authorizedRoleFunctions(data: AuthorizedRoleFunctionsParams) {
  if (data.roleFolderPermissions && data.roleFolderPermissions.length === 0) {
    data.roleFolderPermissions = null;
  }
  if (data.roleMenuPermissions && data.roleMenuPermissions.length === 0) {
    data.roleMenuPermissions = null;
  }
  return req.post<boolean>({
    url: Api.authorizedRoleFunctions,
    data,
  });
}

export function removeAuthorizedRoleUsers(data: AuthorizedRoleUsersParams) {
  return req.post<boolean>({
    url: Api.removeAuthorizedRoleUsers,
    data,
  });
}

export function authorizedRoleUsers(data: AuthorizedRoleUsersParams) {
  return req.post<boolean>({
    url: Api.authorizedRoleUsers,
    data,
  });
}

export function getFunctionsByUserId(params: { userId: ID }, useGlobalLoading = false) {
  return req.get<RoleFunctionMenuItem[]>(
    {
      url: PermissonApi.getFunctionsByUserId,
      params,
    },
    {
      useGlobalLoading,
    }
  );
}

export function getFunctions(options: RequsetOptons) {
  return req.get<RoleFunctionMenuItem[]>(
    {
      url: PermissonApi.getFunctions,
    },
    options
  );
}

export function getRoleById(roleId: string, loading = true) {
  return req.commonPost<RoleItem>(Api.getRoleById, { roleId }, { useGlobalLoading: loading });
}
